//
//  WriteCommentViewController.m
//  TestARC
//
//  Created by wuxiaoquan on 13-4-7.
//
//

#define PlaceHoderText @"评价:20字以上"

#import "WriteCommentViewController.h"
#import "UserManager.h"

@interface WriteCommentViewController ()

@end

@implementation WriteCommentViewController
@synthesize textView,ratingView;
@synthesize textField,selectPicker,doneToolbar,diseaseArray,overylay;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //self.overylay.hidden = YES;
    //self.title = @"写评论";
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStyleDone target:self action:@selector(submitComment)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    
    [self.textView setDelegate:self];
    [self.textView setReturnKeyType:UIReturnKeyDone];
    [self.textView setText:PlaceHoderText];
    [self.textView setTextColor:[UIColor lightGrayColor]];
    
    [self.ratingView setImagesDeselected:@"0.png" partlySelected:@"1.png" fullSelected:@"2.png" andDelegate:self];
	[self.ratingView displayRating:0.0];
    
    //-------picker-------
    textField.inputView = selectPicker;
    textField.inputAccessoryView = doneToolbar;
    [textField becomeFirstResponder];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    if(request != nil)
    {
        [request clearDelegatesAndCancel];
        request = nil;
    }
    self.textView = nil;
    self.ratingView = nil;
    request4Comment = nil;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL) textViewShouldBeginEditing:(UITextView *)textView
{
    if (self.textView.textColor == [UIColor lightGrayColor]) {
        self.textView.text = @"";
        self.textView.textColor = [UIColor blackColor];
    }
    
    return YES;
}

-(void) textViewDidChange:(UITextView *)textView
{
    if(self.textView.text.length == 0){
        self.textView.textColor = [UIColor lightGrayColor];
        self.textView.text = PlaceHoderText;
        [self.textView resignFirstResponder];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if([text isEqualToString:@"\n"]) {
        [self.textView resignFirstResponder];
        if(self.textView.text.length == 0){
            self.textView.textColor = [UIColor lightGrayColor];
            self.textView.text = PlaceHoderText;
            [self.textView resignFirstResponder];
        }
        return NO;
    }
    
    return YES;
}

//------rating-------
-(void)ratingChanged:(float)newRating {
	NSLog(@"rating=%@",[NSString stringWithFormat:@" %1.1f", newRating]); 
}


- (void) submitComment
{
    
    
    if (self.textField.text.length <= 0) {
        UIAlertView *av = [[UIAlertView alloc]
                           initWithTitle:@"不能提交"
                           message:@"请选择治疗疾病"
                           delegate:self
                           cancelButtonTitle:@"OK"
                           otherButtonTitles:nil];
        [av show];
        return;
    }
    
    float rating = [self.ratingView rating];
    if (rating <= 0.0) {
        UIAlertView *av = [[UIAlertView alloc]
                           initWithTitle:@"不能提交"
                           message:@"请点击星星为药品打分"
                           delegate:self
                           cancelButtonTitle:@"OK"
                           otherButtonTitles:nil];
        [av show];
        return;
    }
    
    NSString *comment = self.textView.text;
    if (self.textView.textColor == [UIColor lightGrayColor] || comment.length == 0) {
        UIAlertView *av = [[UIAlertView alloc]
                           initWithTitle:@"不能提交"
                           message:@"请为药品写20字以上评语"
                           delegate:self
                           cancelButtonTitle:@"OK"
                           otherButtonTitles:nil];
        [av show];
        return;
    }
    
    //检测完毕之后直接提交

    [self showWaitView:nil];
    
    //NSArray  * array= [self.name componentsSeparatedByString:@" "];
    //NSString * nameStr = [NSString stringWithFormat:@"%@  %@",[array objectAtIndex:0],[array objectAtIndex:1]];
    //NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    
    NSString * drugname = self.title;
    NSString * diseasename = self.textField.text;
    //diseasename = [diseasename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    int score = [self.ratingView rating];
    NSString * commenttext = self.textView.text;
    NSString * userid = @"guest";
    NSString * username = @"匿名";
    NSString * currentUserID = [UserManager getCurrentUser].userName;
    NSString * currentUserName = [UserManager getCurrentUser].name;
    if (currentUserID.length > 0) {
        userid = currentUserID;
        username = currentUserName;
    }
    NSString * checksum = [[NSString stringWithFormat:@"%d%@yaoxia",score,userid]md5];
    //可选
    NSString *role = @"";
    NSString *age = @"";
    NSString *sex = @"";
    NSString *isvisble = @"";
    NSString *tastetime = @"";
    
    NSString *URL_DETAIL = [NSString stringWithFormat:@"http://www.yaoxia.com/ajaxServlet"];
    NSURL *url = [NSURL URLWithString:URL_DETAIL];
    request4Comment = [ASIFormDataRequest requestWithURL:url];
    
    [request4Comment setPostValue:@"addcommentformobile" forKey:@"style"];
    [request4Comment setPostValue:drugname forKey:@"drugname"];
    [request4Comment setPostValue:diseasename forKey:@"diseasename"];
    [request4Comment setPostValue:[NSString stringWithFormat:@"%d",score]  forKey:@"score"];
    [request4Comment setPostValue:commenttext  forKey:@"commenttext"];
    [request4Comment setPostValue:userid  forKey:@"userid"];
    [request4Comment setPostValue:username  forKey:@"username"];
    [request4Comment setPostValue:checksum forKey:@"checksum"];
    [request4Comment setPostValue:role forKey:@"role"];
    [request4Comment setPostValue:age forKey:@"age"];
    [request4Comment setPostValue:sex forKey:@"sex"];
    [request4Comment setPostValue:isvisble forKey:@"isvisble"];
    [request4Comment setPostValue:tastetime forKey:@"tastetime"];
    
    NSLog(@"\n请求写评论接口的参数如下：\n\
          url=%@\n\
          style=addcommentformobile\n\
          drugname=%@\n\
          diseasename=%@\n\
          score=%@\n\
          commenttext=%@\n\
          userid=%@\n\
          checksum=%@\n\
          username=%@\n\
          role=%@\n\
          age=%@\n\
          sex=%@\n\
          isvisble=%@\n\
          tastetime=%@\n\
          ",URL_DETAIL,drugname,diseasename,[NSString stringWithFormat:@"%d",score],commenttext,userid,checksum
          ,username,role,age,sex,isvisble,tastetime);
    
    [request4Comment setCompletionBlock:^{
        
        [self hideWaitView];
        
        // Use when fetching text data
        NSString *responseString = [request4Comment responseString];
        
        NSLog(@"\nresponseString = %@",responseString);
        id json = [responseString JSONValue];
        if ([[json objectForKey:@"code"]intValue] != 200) {
            NSString *message = [json objectForKey:@"message"];
            UIAlertView *alert = [[UIAlertView alloc]
                                  initWithTitle:@"错误"
                                  message:message
                                  delegate:self
                                  cancelButtonTitle:@"OK"
                                  otherButtonTitles:nil];
            [alert show];
            return ;
        }
        else if ([[json objectForKey:@"code"]intValue] == 200)
        {
            UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"消息"
                              message:@"评论成功!"
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
            [alert show];
            return ;
        }
        
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request4Comment setFailedBlock:^{
        
        [self hideWaitView];
        
        NSError *error = [request4Comment error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"无法连接到网络"
                              message:nil
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request4Comment startAsynchronous];
}

//---------picker--------------
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return [diseaseArray count];
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return [[diseaseArray objectAtIndex:row] objectForKey:@"name"];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.overylay.hidden = NO;
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.overylay.hidden = YES;
}

- (IBAction)selectButton:(id)sender {
    NSInteger row = [selectPicker selectedRowInComponent:0];
    self.textField.text = [[diseaseArray objectAtIndex:row]objectForKey:@"name"];
    [textField endEditing:YES];
}

- (IBAction)cancelButton:(id)sender
{
    if (textField.text.length <= 0) {
        NSInteger row = [selectPicker selectedRowInComponent:0];
        self.textField.text = [[diseaseArray objectAtIndex:row]objectForKey:@"name"];
    }
    [textField endEditing:YES];
}


@end
